<template>
  <div>
    <a-row>
      <a-col :span="3" style="text-align: right">关联课程服务：</a-col>
      <a-col :span="20">
        <a @click="learningChangeVisible = true">添加课程服务</a>
        <a-table
          v-if="dataList.length > 0"
          :columns="columnsList"
          ref="table"
          :data-source="dataList"
          :pagination="pagination"
          :rowKey="record => record.courseServiceId"
        >
          <span slot="number" slot-scope="text, record">
            <template>
              <a-input
                v-model="record.number"
                @keyup="numbers(record)"
                placeholder="请填写"
              ></a-input>
            </template>
          </span>
          <span slot="money" slot-scope="text, record">
            <template>
              {{ (record.number && (record.number * record.servicePrice).toFixed(2)) || 0 }}
            </template>
          </span>
          <span slot="action" slot-scope="text, record">
            <template>
              <a @click="handleDelete(record)">删除</a>
            </template>
          </span>
        </a-table>
      </a-col>
    </a-row>
    <div style="text-align: center" :style="{ marginTop: dataList.length > 0 ? '0' : '500px' }">
      <a-button @click="prevStep" style="margin-right: 20px"> 上一步 </a-button>
      <a-button type="primary" @click="nextStep"> 下一步 </a-button>
    </div>
    <a-modal
      title="添加课程服务"
      :visible="learningChangeVisible"
      @ok="learningChangeHandleOk"
      @cancel="learningChangeHandleCancel"
      okText="确定"
      cancelText="取消"
      width="50%"
    >
      <div class="form-wrapper">
        <a-form layout="inline">
          <a-row :gutter="48">
            <a-col :md="8" :sm="24">
              <a-form-item label="课程目录">
                <a-cascader
                  :field-names="{ label: 'value', value: 'id', children: 'children' }"
                  :options="directoryOptions"
                  :load-data="loadData"
                  placeholder="请选择课程目录"
                  change-on-select
                  v-model="queryParam.directory"
                />
              </a-form-item>
            </a-col>
            <a-col :md="8" :sm="24">
              <a-form-item label="课程服务ID">
                <a-input v-model="queryParam.id" placeholder="请输入课程服务ID" />
              </a-form-item>
            </a-col>
            <a-col :md="8" :sm="24">
              <a-form-item label="学习包名称">
                <a-input v-model="queryParam.name" placeholder="请输入服务名称" />
              </a-form-item>
            </a-col>
            <a-col :md="24" :sm="24">
              <span class="table-page-search-submitButtons" style="float: right">
                <a-button type="primary" @click="search">筛选</a-button>
                <a-button style="margin-left: 8px" @click="reset">重置</a-button>
              </span>
            </a-col>
          </a-row>
        </a-form>
      </div>
      <a-table
        :rowSelection="rowSelection"
        :columns="learningChangeColumns"
        :data-source="learningChangeData"
        :pagination="learningChangePagination"
        :rowKey="record => record.courseServiceId"
      >
      </a-table>
    </a-modal>
  </div>
</template>
<script>
import { directory, courseList } from '@/api/product/goods'
const columnsList = [
  {
    title: '课程服务ID',
    dataIndex: 'courseServiceId',
    align: 'center'
  },
  {
    title: '服务名称',
    dataIndex: 'courseServiceName',
    align: 'center'
  },
  {
    title: '课程目录',
    dataIndex: 'examName',
    align: 'center'
  },
  {
    title: '服务内容',
    dataIndex: 'serviceContent',
    align: 'center'
  },
  {
    title: '服务单价',
    dataIndex: 'servicePrice',
    align: 'center'
  },
  {
    title: '服务次数',
    dataIndex: 'number',
    scopedSlots: { customRender: 'number' },
    align: 'center'
  },
  {
    title: '服务价格',
    scopedSlots: { customRender: 'money' },
    align: 'center'
  },
  {
    title: '操作',
    dataIndex: 'action',
    scopedSlots: { customRender: 'action' },
    align: 'center'
  }
]
const learningChangeColumns = [
  {
    title: '课程服务ID',
    dataIndex: 'courseServiceId',
    align: 'center'
  },
  {
    title: '服务名称',
    dataIndex: 'courseServiceName',
    align: 'center'
  },
  {
    title: '服务内容',
    dataIndex: 'serviceContent',
    align: 'center'
  },
  {
    title: '服务单价',
    dataIndex: 'servicePrice',
    align: 'center'
  }
]
export default {
  data () {
    return {
      columnsList,
      dataList: JSON.parse(localStorage.getItem('learning')) || [],
      pagination: {
        defaultCurrent: 1, // 默认当前页数
        defaultPageSize: 10, // 默认当前页显示数据的大小
        total: 0, // 总数，必须先有
        showSizeChanger: true,
        showQuickJumper: true,
        onShowSizeChange: (current, pageSize) => {
          this.pagination.defaultCurrent = 1
          this.pagination.defaultPageSize = pageSize
        },
        // 改变每页数量时更新显示
        onChange: (current, size) => {
          this.pagination.defaultCurrent = current
          this.pagination.defaultPageSize = size
        }
      },
      learningChangeVisible: false,
      learningChangeColumns,
      learningChangeData: [],
      selectedRows: [],
      selectedRowKeys: [],
      learningChangePagination: {
        defaultCurrent: 1, // 默认当前页数
        defaultPageSize: 10, // 默认当前页显示数据的大小
        total: 0, // 总数，必须先有
        showSizeChanger: true,
        showQuickJumper: true,
        onShowSizeChange: (current, pageSize) => {
          this.learningChangePagination.current = 1
          this.learningChangePagination.defaultCurrent = 1
          this.learningChangePagination.defaultPageSize = pageSize
        },
        // 改变每页数量时更新显示
        onChange: (current, size) => {
          this.learningChangePagination.current = current
          this.learningChangePagination.defaultCurrent = current
          this.learningChangePagination.defaultPageSize = size
        }
      },
      queryParam: {
        directory: [],
        id: '',
        name: ''
      },
      directoryOptions: []
    }
  },
  computed: {
    rowSelection () {
      const that = this
      return {
        selectedRowKeys: this.selectedRowKeys,
        onChange: (selectedRowKeys, selectedRows) => {
          that.selectedRowKeys = selectedRowKeys
        },
        onSelectAll: (isSelected, selectedRows, changedRows) => {
          if (isSelected) {
            that.selectedRows = [...that.selectedRows, ...selectedRows]
          } else {
            const removedIds = changedRows.map(i => i.studyPackageId)
            that.selectedRows = that.selectedRows.filter(i => !removedIds.includes(i.courseId))
          }
        },
        onSelect: (record, isSelected) => {
          if (isSelected) {
            that.selectedRows.push(record)
          } else {
            that.selectedRows = that.selectedRows.filter(i => i.studyPackageId !== record.courseId)
          }
        },
        getCheckboxProps: (record) => ({
          props: {
            checked: that.selectedRowKeys.indexOf(record.studyPackageId) > -1
          }
        })
      }
    }
  },
  mounted () {
    this.getDirectory()
    this.getData()
  },
  methods: {
    // 限制数字及0
    numbers (re) {
      re.number = re.number.replace(/\D/g, '')
      re.number = re.number.replace('0', '')
    },
    // 获取课程服务列表数据
    getData () {
      const data = {
        currentPage: this.pagination.defaultCurrent,
        pageSize: this.pagination.defaultPageSize
      }
      if (this.queryParam.id !== '') {
        data.courseServiceId = this.queryParam.id
      }
      if (this.queryParam.name !== '') {
        data.courseServiceName = this.queryParam.name
      }
      if (this.queryParam.directory[0]) {
        data.directoryId = this.queryParam.directory[0]
      }
      if (this.queryParam.directory[1]) {
        data.examId = this.queryParam.directory[1]
      }
      if (this.queryParam.directory[2]) {
        data.subjectId = this.queryParam.directory[2]
      }
      if (this.queryParam.directory[3]) {
        data.fourExamId = this.queryParam.directory[3]
      }
      if (this.queryParam.directory[4]) {
        data.fiveExamId = this.queryParam.directory[4]
      }
      if (this.queryParam.directory[5]) {
        data.sixExamId = this.queryParam.directory[5]
      }
      courseList(data).then(res => {
        if (res.code === '1') {
          this.learningChangePagination.total = res.data.totalSize
          this.learningChangeData = res.data.rows
        } else {
          this.$message.error(res.msg)
        }
      }).catch(err => {
        this.$message.error(err.msg)
      })
    },
    // 下一步
    nextStep () {
      if (this.dataList.length > 0) {
        if (this.dataList.every(item => item.number > 0)) {
          localStorage.setItem('learning', JSON.stringify(this.dataList))
          this.$emit('nextStep')
        } else {
          this.$message.error('请填写服务次数')
        }
      } else {
        this.$message.error('请添加课程服务')
      }
    },
    // 上一步
    prevStep () {
      this.$emit('prevStep')
    },
    // 表格列表删除
    handleDelete (row) {
      console.log(row)
    },
    // 表格多选
    onSelectChange (selectedRowKeys, selectedRows) {
      this.selectedRows = selectedRows
      this.selectedRowKeys = selectedRowKeys
    },
    // 添加课程服务筛选
    search () {
      this.getData()
    },
    // 重置
    reset () {
      this.selectedRows = []
      this.selectedRowKeys = []
      this.learningChangePagination.current = 1
      this.learningChangePagination.defaultCurrent = 1
      this.queryParam = {
        directory: [],
        id: '',
        name: ''
      }
      this.getData()
    },
    // 添加课程服务确定
    learningChangeHandleOk () {
      if (this.selectedRows.length === 0) {
        this.$message.error('请添加课程服务')
        return false
      }
      const learning = []
      this.dataList.forEach(item => {
        learning.push(item.courseServiceId)
      })
      this.selectedRows.forEach(item => {
        if (!learning.includes(item.courseServiceId)) {
          this.dataList.push(item)
        }
      })
      this.selectedRowKeys = []
      this.selectedRows = []
      this.queryParam = {
        directory: [],
        id: '',
        name: ''
      }
      this.learningChangeVisible = false
    },
    // 添加课程服务取消
    learningChangeHandleCancel () {
      this.selectedRows = []
      this.selectedRowKeys = []
      this.learningChangePagination.current = 1
      this.learningChangePagination.defaultCurrent = 1
      this.queryParam = {
        directory: [],
        id: '',
        name: ''
      }
      this.learningChangeVisible = false
    },
    // 获取课程目录
    getDirectory () {
      const data = {
        type: 0,
        directoryLevel: 1
      }
      directory(data).then(res => {
        if (res.code === '1') {
          res.data.forEach(item => {
            item.isLeaf = false
          })
          this.directoryOptions = res.data
        }
      }).catch(err => {
        this.$message.error(err.msg)
      })
    },
    // 课程目录二级-六级
    loadData (selectedOptions) {
      const targetOption = selectedOptions[selectedOptions.length - 1]
      const data = {
        type: 1,
        parentId: targetOption.id,
        directoryLevel: 2
      }
      targetOption.loading = true
      directory(data).then(res => {
        if (res.code === '1') {
          if (res.data.length > 0) {
            res.data.forEach(item => {
              item.isLeaf = false
            })
            targetOption.loading = false
            targetOption.children = [...res.data]
          } else {
            targetOption.loading = false
            this.$message.error('暂无更多数据')
          }
        } else {
          targetOption.loading = false
          this.$message.error(res.msg)
        }
        this.directoryOptions = [...this.directoryOptions]
      }).catch(err => {
        this.$message.error(err.msg)
        targetOption.loading = false
      })
    }
  }
}
</script>
<style scoped>
</style>
